//
//  BESelectImageController.swift
//  BEGlobalOiler
//
//  Created by KKING on 16/7/26.
//  Copyright © 2016年 Bullseye Energy pte ltd. All rights reserved.
//

import UIKit
import HMImagePicker

private let pictureSelecID = "pictureSelecID"

private let row: CGFloat = 4
private let itemMargin: CGFloat = 3

private let maxImageCount = 9

class BESelectImageController: UICollectionViewController {
    
    //用于定位选中的图片
    var selectedAssets:[PHAsset] = [PHAsset]()
    
    var images:[UIImage] = [UIImage]()
    
    //    init() {
    //        let layout = UICollectionViewFlowLayout()
    //        let itemWidth = (ScreenWidth - (row + 1) * itemMargin) / row
    //        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    //        layout.minimumLineSpacing = itemMargin
    //        layout.minimumInteritemSpacing = itemMargin
    //
    //        super.init(collectionViewLayout: layout)
    //        self.collectionView?.backgroundColor = UIColor.whiteColor()
    //
    //        self.collectionView?.contentInset = UIEdgeInsetsMake(itemMargin, itemMargin, 0, itemMargin)
    //        self.collectionView?.registerClass(BEPictureSelecCell.self, forCellWithReuseIdentifier: pictureSelecID)
    //    }
    
    required init?(coder aDecoder: NSCoder) {
        let layout = UICollectionViewFlowLayout()
//        let itemWidth = ((SCREEN_WIDTH - 16) - (row + 1) * itemMargin) / row
        layout.itemSize = CGSize(width: 85, height: 106)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = 2
        layout.scrollDirection = .horizontal
        
        super.init(collectionViewLayout: layout)
        self.collectionView?.backgroundColor = UIColor.white
//        self.collectionView?.scrollEnabled = false
        self.collectionView?.contentInset = UIEdgeInsetsMake(itemMargin, itemMargin, itemMargin, itemMargin)
        self.collectionView?.register(BEPictureSelecCell.self, forCellWithReuseIdentifier: pictureSelecID)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    
}

//数据源方法
extension BESelectImageController{
    
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //有关return item的判断
        let delta = images.count == maxImageCount ? 0 : 1
        return images.count + delta
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureSelecID, for: indexPath as IndexPath) as! BEPictureSelecCell
        
        cell.backgroundColor = UIColor(red: 0 / 255.0, green: 148 / 255.0, blue: 242 / 255.0, alpha: 1)
        //images.count == indexPath.item
        //巧妙应用,,把最后一个item的图片设置为空,然后在cell里面进行判断,隐藏图片为nil的cell的deleteBtn
        //        print(images.count)
        //        print(indexPath.item)
        
        if images.count == indexPath.item {
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
        
        cell.picSelDelegate = self
        return  cell
    }
}

extension BESelectImageController: KKPictureSelecCellDelegate {
    
    func addPicture() {
        //        print("添加")
        //        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum){
        //            print("没有访问权限")
        //            return
        //        }
        //        let picker = UIImagePickerController()
        //        picker.delegate = self
        //        //图片允许编辑
        //        //        picker.allowsEditing = true
        //        presentViewController(picker, animated: true, completion: nil)
        
        let picker = HMImagePickerController(selectedAssets: selectedAssets)
        
        // 设置图像选择代理
        picker.pickerDelegate = self;
        // 设置目标图片尺寸
        picker.targetSize = CGSize(width: 600, height: 600)
        // 设置最大选择照片数量
        picker.maxPickerCount = 9;
        present(picker, animated: true, completion: nil)
        
        
        picker.modalPresentationStyle = .currentContext
        
    }
    
    func deletePicture(selCell: UICollectionViewCell) {
        
        guard let indexPath = collectionView?.indexPath(for: selCell) else{
            return
        }

        images.remove(at: indexPath.item)
        selectedAssets.remove(at: indexPath.item)
        
        collectionView?.reloadData()
    }
}



extension BESelectImageController: HMImagePickerControllerDelegate{
    
    func imagePickerController(_ picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        // 记录图像，方便在 CollectionView 显示
        self.images = images
        // 记录选中资源集合，方便再次选择照片定位
        self.selectedAssets = selectedAssets!
        
        collectionView?.reloadData()
        dismiss(animated: true, completion: nil)
        
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print(picker)
    }
    
}


//系统方式选择图片的代理
extension BESelectImageController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //image添加到数组
        images.append(image)
        self.collectionView?.reloadData()
        
        self.dismiss(animated: true, completion: nil)
    }
}







//cell ---> 制定协议和代理
protocol KKPictureSelecCellDelegate: NSObjectProtocol {
    
    func addPicture()
    func deletePicture(selCell: UICollectionViewCell)
    
}



class BEPictureSelecCell: UICollectionViewCell {
    
    var image: UIImage?{
        didSet{
            
            deleteBtn.isHidden = image == nil
            addBtn.setImage(image, for: .normal)
        }
    }
    
    //代理属性
    weak var picSelDelegate: KKPictureSelecCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let colValue: CGFloat = 237.0 / 255.0
        //设置背景颜色和图片颜色一样,用sRGB取色
        backgroundColor = UIColor(red: colValue, green: colValue, blue: colValue, alpha: 1)
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setUpUI() {
        
        contentView.addSubview(addBtn)
        
        contentView.addSubview(deleteBtn)
        
        
        addBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView.snp.edges)
        }
        
        deleteBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(0)
        }
        
        addBtn.addTarget(self, action: #selector(BEPictureSelecCell.addBtnDidClick), for: .touchUpInside)
        deleteBtn.addTarget(self, action: #selector(BEPictureSelecCell.deleteBtnDidClick), for: .touchUpInside)
        
    }
    
    
    //两个按钮的点击方法
    @objc private func addBtnDidClick() {
        
        //如果当前cell图片不为空,则直接返回
        if image != nil {
            return
        }
        
        picSelDelegate?.addPicture()
    }
    @objc private func deleteBtnDidClick() {
        //把cell回传给控制器
        picSelDelegate?.deletePicture(selCell: self)
    }
    
    
    
    //懒加载控件
    private lazy var addBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage( UIImage(named: "compose_pic_add"), for: .normal)
        
        btn.imageView?.contentMode = .scaleAspectFill
        btn.imageView?.clipsToBounds = true
        
        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
        
        let btn = UIButton()
        btn.setBackgroundImage( UIImage(named: "compose_photo_close"), for: .normal)
        
        return btn
        
    }()
}

